import { DavinciBlock, SourceType } from './custom-types.ts';
import { h, VNode } from 'snabbdom';
import { IDomEditor, SlateElement, DomEditor, SlateTransforms, SlateNode } from '@wangeditor/editor';

export function renderDavinciBlock(elem: SlateElement, children: VNode[] | null, editor: IDomEditor): VNode {
	const {
		content,
		color = '#000',
		selectedColor = '#000',
		prefix = '#',
		brace = true,
		backgroundColor = 'rgba(0,0,0,0.1)',
		attrs = {},
		fontSize = '16px',
		fontFamily = '',
		contextmenuCan = false,
		clickCan = false,
		isEmbedSource = false,
		sourceType = 'Text',
		src = ''
	} = elem as DavinciBlock;

	const selected = DomEditor.isNodeSelected(editor, elem);

	const on = {
		async contextmenu(e: Event) {
			e.preventDefault();
			if (!contextmenuCan) return;
			const deleteNode = () => {
				let nodes = SlateNode.nodes(editor, {
					pass: n => {
						return n == elem;
					}
				});
				[...nodes].forEach(([node, path]) => {
					if (node == elem) {
						const selection = {
							anchor: { path, offset: 0 },
							focus: { path, offset: 0 }
						};
						editor.select(selection);
						SlateTransforms.removeNodes(editor, {
							at: path,
							hanging: true
						});
					}
				});
			};
			await config.EXTEND_CONF?.['davinci-block']?.onRightClick?.(elem, deleteNode);
		},
		click() {
			if (!clickCan) return;
			config.EXTEND_CONF?.['davinci-block']?.onClick?.(elem);
		}
	};
	// @ts-ignore
	const config = editor.getConfig();
	const davinciVnode = h(
		'span',
		{
			props: { contentEditable: false }, // HTML 属性，驼峰式写法
			style: {
				display: 'inline-block',
				padding: '0 3px',
				margin: '0 1px',
				color: selected ? selectedColor : color,
				background: backgroundColor,
				fontSize,
				fontFamily: fontFamily,
				fontWeight: 'bold',
				cursor: 'pointer',
				animation: selected ? 'davinci-block-blink 1s linear 0s infinite' : 'none'
			},
			dataset: { content, type: 'davinci-block' },
			attrs: {
				...attrs
			},
			on
		},
		[`${prefix}${brace ? '{' + content + '}' : content}`]
	);

	const style = {
		maxWidth: '500px',
		cursor: 'pointer',
		margin: '0 1px',
		animation: selected ? 'davinci-block-blink 1s linear 0s infinite' : 'none',
		userDrag: 'none',
		verticalAlign: 'middle',
		'-webkit-user-drag': 'none'
	};
	const enbedSource = {
		Text: davinciVnode,
		Image: h('img', { src, style, on }, ''),
		Audio: h('audio', { src, style, props: { controls: true }, on }, ''),
		Video: h('video', { src, style, props: { controls: true }, on }, '')
	};
	// let sourceType: keyof typeof enbedSource = 'Image';
	if (isEmbedSource) {
		if (!src) {
			let id = attrs['data-woId'];
			if (id) {
				config.EXTEND_CONF?.getURLWithId?.(id).then(res => {
					if (res) {
						const props = {
							...elem,
							...res
						};
						SlateTransforms.setNodes(editor, props, { at: DomEditor.findPath(editor, elem) });
					}
				});
			}
		}
	}
	const embedVNode = isEmbedSource ? enbedSource[sourceType] : davinciVnode;
	return config.viewMode == 0 ? embedVNode : davinciVnode;
}

const conf = {
	type: 'davinci-block', // 节点 type ，重要！！！
	renderElem: renderDavinciBlock
};

export default conf;
